from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response

from goods.models import SKU
from .models import User
from django_redis import get_redis_connection
# Create your views here.

########################################### 以下内容：注册—验证用户名 一级视图##########################################################
class RegisterUsernameCountAPIView(APIView):

    def get(self,request,username):
        count = User.objects.filter(username=username).count()

        data = {
            'count':count,
            'username':username
        }
        return Response(data)

########################################### 以下内容：注册—验证手机号 一级视图##########################################################
class RegisterPhoneCountAPIView(APIView):

    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'count':count,
            'mobiles':mobile
        }
        return Response(data)

########################################### 以下内容：注册提交 三级视图##########################################################
from .serializers import RegisterCreateSerializer
class RegisterCreateView(CreateAPIView):
    serializer_class = RegisterCreateSerializer

########################################### 以下内容：个人中心 一级视图##########################################################
# from rest_framework.permissions import IsAuthenticated
# from .serializers import UserCenterInfoSerializer
# from rest_framework import status
# class UserCenterInfoAPIView(APIView):
#
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#         #1.通过request中传递的用户信息检测用户的登录状态：
#         # user = request.user
#         # if not user:
#         #     return Response(status=status.HTTP_400_BAD_REQUEST)
#
#         #2.从token数据中提取用户信息
#         from rest_framework_jwt.settings import api_settings
#         data = request.auth
#         jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
#         jwt_payload_get_userid_handler = api_settings.JWT_PAYLOAD_GET_USER_ID_HANDLER
#         jwt_payload_get_username_handler = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER
#
#         payload = jwt_decode_handler(data)
#         user_id = jwt_payload_get_userid_handler(payload)
#         username = jwt_payload_get_username_handler(payload)
#
#         try:
#             user = User.objects.get(id=user_id,username = username)
#         except User.DoesNotExist:
#             return Response(status=status.HTTP_400_BAD_REQUEST)
#
#
#         serializer = UserCenterInfoSerializer(user)
#
#         return Response(serializer.data)


########################################### 以下内容：个人中心 三级视图##########################################################
from rest_framework.generics import RetrieveAPIView
from .serializers import UserCenterInfoSerializer
from rest_framework.permissions import IsAuthenticated

class UserCenterInfoAPIView(RetrieveAPIView):

    serializer_class = UserCenterInfoSerializer
    permission_classes = [IsAuthenticated]

    queryset = User.objects.all()

    def get_object(self):
        return  self.request.user


########################################### 以下内容：设置邮箱 一级视图##########################################################
from .serializers import UserEmailSerializer
from rest_framework.permissions import IsAuthenticated
class UserEmailAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self,request):

        serializer = UserEmailSerializer(instance=request.user,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


########################################### 以下内容：邮箱激活 一级视图##########################################################
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from mall import settings
from rest_framework import status
class UserEmailVerificationAPIView(APIView):

    def get(self,request):

        token = request.query_params.get('token')
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        try:
            serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
            data = serializer.loads(token)
        except BadData:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user_id =data.get('id')
        email = data.get('email')

        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user.email_active =True
        user.save()

        return Response({'message':'ok'})



#######################################《《《 以下内容：收货地址管理 》》》#####################################################
from .serializers import AddressAddSerializer
from .models import Address

########################## 以下内容：新增地址 一级视图####################################
class AddressListView(APIView):

    def post(self,request):
        serializer = AddressAddSerializer(data=request.data,context={'request':request,'view':self})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def get(self,request):
        user = request.user
        addr = Address.objects.filter(user = user.id).all()
        serializer = AddressAddSerializer(addr,many=True)

        default_addr = user.default_address.id
        if not default_addr:
            default_addr=1
        data = {
            'addresses':serializer.data,
            'limit':20,
            'default_address_id':default_addr
        }
        return Response(data=data)

########################## 以下内容：修改收件地址 一级视图####################################
class AddressModifyView(APIView):

    def delete(self,request,pk):
        addr = Address.objects.get(id = pk)
        addr.delete()
        return Response({'message':'删除成功'})

    def put(self,request,pk):
        addr = Address.objects.get(id =pk)
        serializer = AddressAddSerializer(instance=addr,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

########################## 以下内容：设置默认收件地址 一级视图####################################
class SetDefaultAddressView(APIView):
    def put(self,request,pk):
        addr = Address.objects.get(id=pk)
        if not addr:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user = request.user
        user.default_address = addr
        user.save()
        return Response({'message':'设置成功'})



#######################################《《《 以下内容：个人浏览记录 》》》#####################################################
class BrowerHistoryView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self,request):
        sku_id = request.data.get('sku_id')
        user_id = request.user.id
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise Exception('该产品不存在')

        redis = get_redis_connection('history')
        redis.lrem('history_%s'%user_id,0,sku_id)
        redis.lpush('history_%s'%user_id,sku_id)

        return Response({'message':'OK'})

    def get(self,request):
        user_id = request.user.id
        try:
            User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise  Exception('用户不存在')

        redis = get_redis_connection('history')
        sku_ids = redis.lrange('history_%s'%user_id,0,5)
        sku = []
        for sku_id in sku_ids:
            sku_obj = SKU.objects.get(pk = sku_id)
            sku.append(sku_obj)

        from goods.serializers import SKUSerializer
        serializer = SKUSerializer(sku,many=True)

        return Response(serializer.data)

#######################################
# 以下内容：用户登录，且验证成功后，重写ObtainJSONWebToken的post方法，合并本地购物车到数据库中
# #####################################################
from rest_framework_jwt.views import ObtainJSONWebToken
from apps.carts.utils import merge_cookie_to_redis
class ObtainJsonWebTokenView(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):

        response = super().post(request)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            if user is None:
                return Response({'message': '该用户不存在'}, status=status.HTTP_400_BAD_REQUEST)

            cart_cookie = request.COOKIES.get('cart')
            if cart_cookie is None:
                pass
            else:
                response = merge_cookie_to_redis(user,cart_cookie,response)

        return response


#######################################《《《 以下内容：修改密码》》》#####################################################
class Change_Password_Viwe(APIView):

    permission_classes = [IsAuthenticated]

    def put(self,request,user_id):
        user = User.objects.get(id=user_id)
        old_pswd = request.data.get('old_password')
        new_pswd = request.data.get('password')
        new_pswd2 = request.data.get('password2')

        if old_pswd==new_pswd:
            return Response({'message':'新旧密码一致，请重新输入！'},status=status.HTTP_400_BAD_REQUEST)
        if new_pswd != new_pswd2:
            return Response({'message':'新密码两次输入不一致！'},status=status.HTTP_400_BAD_REQUEST)

        if user.check_password(old_pswd):
            user.set_password(new_pswd)
            user.save()
            return Response()
        else:
            return Response({'message':'密码验证失败！'},status=status.HTTP_406_NOT_ACCEPTABLE)